package cn.edu.njust.control;

import cn.edu.njust.pojo.Result;
import cn.edu.njust.service.ResultService;
import cn.edu.njust.service.impl.ResultServiceImpl;
import cn.edu.njust.util.ExcelUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
/*
@Controller
@RequestMapping("/result")
*/
@WebServlet(name = "resultServlet", value = "/resultServlet")
public class ResultController extends HttpServlet {

/*
    @RequestMapping(value = "/import",method = RequestMethod.POST)
*/
    static ResultService rs = new ResultServiceImpl();
    public static void importResult(@RequestPart("files") MultipartFile file) throws Exception {
        List<Result> results = ExcelUtils.readMultipartFile(file, Result.class);
        System.out.println("123");
        for (Result result : results){
            System.out.println(result.toString());
            rs.add(result);

        }
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");

        String fileName = request.getParameter("fileName");
        System.out.println(fileName);

        File file = new File("D:/" + fileName);
        MultipartFile file1 = getMultipartFile(file);
        try {
            ResultController.importResult(file1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        response.getWriter().write("success");
//        request.getRequestDispatcher("uploading.jsp").forward(request,response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        this.doGet(request, response);
    }
}
